package com.cxl.demo.controller;


import com.cxl.demo.mapper.ImageMapper;
import com.cxl.demo.util.FileUtil;
import com.cxl.demo.util.StaticValue;
import com.cxl.demo.vo.Image;
import com.cxl.demo.vo.ReturnData;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class PublicController {
        @Autowired
        ImageMapper imageMapper;

        @Autowired
        ReturnData returnData;

    @PostMapping("/UploadImage")
    public ReturnData UploadImage(HttpServletRequest request, @RequestParam("file") MultipartFile[] files){

        Date date= new Date();
        String timestamp = String.valueOf(date.getTime());


        String uploadPath = StaticValue.UPLOAD;

        returnData.setData(null);
        if (files != null && files.length >= 1) {
            BufferedOutputStream bw = null;
            try {
                String fileName = files[0].getOriginalFilename();
                //判断是否有文件
                if (StringUtils.isNoneBlank(fileName)) {
                    //输出到本地路径

                    String format=timestamp;
                    File outFile = new File(uploadPath + format + FileUtil.getFileType(fileName));
                    String path= format + FileUtil.getFileType(fileName);
                    FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile);
                    imageMapper.AddImage(new Image(null,path,timestamp));
                    Integer imageId= imageMapper.getImageNum();
                    returnData.setMsg("上传成功");
                    returnData.setStatus(true);
                    returnData.setData(imageId);

                }
            } catch (Exception e) {
                returnData.setMsg("上传失败");
                returnData.setStatus(false);
            } finally {
                try {
                    if (bw != null) {
                        bw.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return returnData;
    }

}
